//
// Author    : Pablo Bosch 
// Contact   : pboschvivancos@epo.org
// Created   : 08/05/2005
// Last Modif: 09/05/2005
//


var MOD_CTF = {
  seldoc:"",
  tfimpver:"",
  printhook:printtfview
};



// Navigation buttons


//------------------------------------------------------------------------------

function tf_onclickonclaim(cl) {
  html_doselect("seldoc",ALLDOCPNA,"All");
  filter_doselect("List",cl,"edit_features()");
}    

//------------------------------------------------------------------------------

function tf_updadetable(cl,tf,pos,clfull) {
  var bigt=document.getElementById("bigcltable");
  var tf_iter= new claim_features_iterator(cl,"",tf);
  var eq=GetClaimEq(cl);
  var rowobj;
  var idx=pos || document.getElementById("clrow"+cl+"_"+(tf||1)).sectionRowIndex; 

  // update entries
  while(!tf_iter.end()) {
    rowobj=bigt.rows.item(idx++);
    rowobj.id="clrow"+cl+"_"+(tf_iter.gettf());
    
    rowobj.cells.item(0).innerHTML=tf_showtfTD11(cl,tf_iter.gettf(),tf_iter);
    rowobj.cells.item(1).innerHTML=tf_showtfTD12(cl,tf_iter.gettf(),tf_iter,eq);
    rowobj.cells.item(2).innerHTML=tf_showtfTD13(cl,tf_iter.gettf(),clfull);
    
    rowobj=bigt.rows.item(idx++);
    
    rowobj.cells.item(0).innerHTML=tf_showtfTD21(cl,tf_iter.gettf(),tf_iter,eq);
    rowobj.cells.item(1).innerHTML=tf_showtfTD22(cl,tf_iter.gettf(),tf_iter,eq);
    
    tf_iter.next();
  }
}

         
function tf_updatevalfromauto(cl,tf,pn) {
  if(pn) {
    var eq_iter= new EqTF_claim_iterator(cl,tf);
    tf_updateclDESV(cl,pn);
    //alert(cl+" "+pn+" is "+GetClaimDocAutoVal(cl,pn)+ " or "+GetClaimDocVal(cl,pn));
    while(!eq_iter.end()) {
      if(IsClaimInPage(eq_iter.getValue())) { // && is_Tainted(clo)) { 
	tf_updateclDESV(eq_iter.getValue(),pn);
      }
      eq_iter.next();
    }
  }
}

function tf_updatevalfromautoall(cl,tf) {
  var pn=MOD_CTF.seldoc;
  if(GetDocsLength()>=1 &&  MOD_CTF.seldoc) {
    var clists=featureupdatevalfromautoall(cl,tf);
    var mod_iter=clists[pn].iterator();
    var docidx=Doc2DOCPNS(pn);
    
    while(!mod_iter.end()) {
      if(IsClaimInPage(mod_iter.getValue())) { // && is_Tainted(clo)) { 
	// update view of equals       
	tf_updateclDESV(mod_iter.getValue(),pn);
      }
      mod_iter.next();
    }
  }
}


function tf_onchangeheader(cl) {
  var txtarea=document.getElementById("tftxtarea"+cl+"_0");
  SetClaimHeader(cl,txtarea.value);
}

function tf_onstripheader(cl) {
  var txtarea=document.getElementById("tftxtarea"+cl+"_1");  
  var cursorat=html_getCursorPos(txtarea);
 
  var txt1=txtarea.value.substring(0,cursorat); // header
  var txt2=txtarea.value.substring(cursorat,txtarea.value.length);

  SetClaimHeader(cl,txt1);
  SetFeatureDesc(cl,1,txt2);

  edit_features();
}

function tf_onjoinheader(cl) {
  SetFeatureDesc(cl,1,GetClaimHeader(cl)+" "+GetFeatureDesc(cl,1));
  SetClaimHeader(cl,"");
  edit_features();
}

//
// split TF in two 
//
  
function tf_onsplittf(cl,tf,clfull) { 
  var txtarea=document.getElementById("tftxtarea"+cl+"_"+tf);  
  var cursorat=html_getCursorPos(txtarea);


  if(!cursorat) {
    return;
  }

  var txt1=txtarea.value.substring(0,cursorat);
  var txt2=txtarea.value.substring(cursorat,txtarea.value.length);
  
  var cltf_iter= featuresplit(cl,tf,txt1,txt2,MOD_CTF.seldoc).iterator();
  var warnings= new List();
  
  while(!cltf_iter.end()) {
    var ctf=new claim_tf(cltf_iter.getValue());
    if(GetFeatureWarn(ctf.getcl(),ctf.gettf())){
      warnings.push(cltf_iter.getValue());
      html_setwarning("tfwarn"+ctf.getcl()+"_"+ctf.gettf(),GetFeatureWarn(ctf.getcl(),ctf.gettf()));
    }
    if(IsClaimInPage(ctf.getcl())) { // && is_Tainted(clo)) { 	 
      tf_updatetfTD11(ctf.getcl(),ctf.gettf());   
    }
    cltf_iter.next();
  }
    

  if(warnings.length()) {
    alert("Check references to "+cl+"."+tf+" in : "+warnings.getValue());
  }

  // Update view

  var oldrow=document.getElementById("clrow"+cl+"_"+tf);
  if(oldrow) {
    var bigt=document.getElementById("bigcltable");
    var insertidx=document.getElementById("clrow"+cl+"_"+tf).sectionRowIndex;
    var newrow,newcell;
   
   // each TF entry comprises two lines with 3 cells 
    newrow=bigt.insertRow(insertidx);
 
    newrow.insertCell(0).className="NOTOP";
    newcell=newrow.insertCell(1);
    newcell.valign='bottom';
    newcell.className="NOTOP";
    newrow.insertCell(2).rowspan=2;
   
    newrow=bigt.insertRow(insertidx);
    newrow.className="NOBOTTOM";
    newrow.insertCell(0).className="NOBOTTOM";
    newrow.insertCell(1).className="NOBOTTOM";
    newrow.insertCell(2);

    tf_updadetable(cl,tf,insertidx,clfull);

    // update autovalue for all features below tf, for all documents 
    var tf_iter= new claim_features_iterator(cl,"",tf);
    while(!tf_iter.end()) {
      tf_updatevalfromauto(tf_iter.getcl(),tf_iter.gettf(),MOD_CTF.seldoc); // update only current view
      tf_iter.next();
    }    

    // check if in full mode 
    if(clfull && clfull!=cl) {
      var tf_iter= new claim_features_iterator(clfull);
      while(!tf_iter.end()) {
	tf_updatevalfromauto(tf_iter.getcl(),tf_iter.gettf(),MOD_CTF.seldoc); // update only current view
	tf_iter.next();
      }    
    }
      
  } else {
    edit_features();
  }
  
}

//------------------------------------------------------------------------------

//
// join TF and TF-1 into TF-1  
//

// todo , update hint, passage and clar from lost tf
function tf_onjointf(cl,tf,clfull) {  
  var checklist=featuresjoin(cl,tf); // do the join at the tf level
  var cltf_iter= checklist.iterator();
  var warnings= new List();


  while(!cltf_iter.end()) {
    var ctf=new claim_tf(cltf_iter.getValue());
    if(GetFeatureWarn(ctf.getcl(),ctf.gettf())){
      warnings.push(cltf_iter.getValue());
      html_setwarning("tfwarn"+ctf.getcl()+"_"+ctf.gettf(),GetFeatureWarn(ctf.getcl(),ctf.gettf()));
    }
    if(IsClaimInPage(ctf.getcl())) { // && is_Tainted(clo)) { 	 
      tf_updatetfTD11(ctf.getcl(),ctf.gettf());   
    }
    cltf_iter.next();
  }

  if(warnings.length()) {
    alert("Check references to "+cl+"."+tf+" in : "+warnings.getValue());
  }
  
  // overwritten hint may have changed 
 
  if(MOD_CTF.seldoc) tf_onchangetfhint(cl,tf-1,GetPassageHint(cl,tf-1,MOD_CTF.seldoc));
 

  var oldrow=document.getElementById("clrow"+cl+"_"+tf);
  if(oldrow) {
    var bigt=document.getElementById("bigcltable");
    var insertidx=document.getElementById("clrow"+cl+"_"+tf).sectionRowIndex;
    bigt.deleteRow(insertidx);
    bigt.deleteRow(insertidx);
    tf_updadetable(cl,tf-1,"",clfull);    

    // update autovalue for all features below tf, for all documents 
    var tf_iter= new claim_features_iterator(cl,"",tf);
    while(!tf_iter.end()) {
      featureupdatevalfromautoall(tf_iter.getcl(),tf_iter.gettf()); // update forall docs 
      tf_updatevalfromauto(tf_iter.getcl(),tf_iter.gettf(),MOD_CTF.seldoc); // update only current view
      tf_iter.next();
    }

  } else {
    edit_features();
  }
}

//------------------------------------------------------------------------------

//
// Update claim S field 
//

function tf_onchangestrat(cl,doc) {
  var newstrat=html_selected("ssel"+cl+"_"+doc,CLSTRATS);
  var newval=html_selected("vsel"+cl+"_"+doc,CLVALS);
  var pn=GetDocPN(doc);
  // If val is empty,  upgrade val 
  if(!newval) {
    newval=strat2val(newstrat);
  }

  // explicit change requested 
  var taint=new_Taint();
  
  // Apply 
  change_stratdoc_claimlist(cl,prompt_downwards_propagation(cl),newstrat,pn);
  
  if(!is_TaintedFrom(taint,cl)) {
    tf_updateclDESV(cl,pn);
    return;
  }

  // Update view    
  var iter= new PageClaim_Iterator();
  while(!iter.end()) {
    var clo=iter.getValue();
    if(is_TaintedFrom(taint,clo)) { 
      // update view of equals       
      tf_updateclDESV(clo,pn);
      //if(GetClaimEqWarn(clo)) alert(GetClaimEqWarn(clo));
      html_setwarning("cleqwarn"+clo,GetClaimEqWarn(clo));
    }    
    iter.next();   
  }
  tf_updateglobalwarnings();
  tf_updatenotsearchedview();
}

//------------------------------------------------------------------------------

//
// Update claim V field 
//

function tf_onchangeval(cl,doc) {
  // Change value and update view of eq claims 
  var newval=html_selected("vsel"+cl+"_"+doc,CLVALS);
  var newstrat=html_selected("ssel"+cl+"_"+doc,CLSTRATS);
  var pn=GetDocPN(doc);
  
  // If strat if greater than val, downgrade strat 
  if(catcmp(newstrat,newval)==">") {
    newstrat="";
  }
  
  if(!check_val_integrity(cl,pn,newval)) {
    alert("Error: conflicting document values for claims "+cl+" and "+GetClaimDep(cl));  
    html_doselect("vsel"+cl+"_"+doc,CLVALS,GetClaimDocVal(cl,pn));
  } else {  
    SetClaimDocVal(cl,pn,newval);  
    SetClaimDocStrat(cl,newstrat,pn);
        
    // things are changing for claim cl
    new_Taint(cl);
    prompt_val_downwards_propagation(cl,newval,pn);
    fix_val_downwards_propation(cl,pn);
    //fix_downwards_propation(cl,newstrat);  

    // Update view      
    tf_updateclDESV(cl,pn);
    // update view to others
    var cl_iter= new claim_iterator(cl);
    while(!cl_iter.end()) {
      var clo=cl_iter.getValue();	
      updatefromdocs(clo); // do not comment out !
      if(IsClaimInPage(clo)) { // && is_Tainted(clo)) { 
	tf_updateclDESV(clo,pn);
      }
      cl_iter.next();   
    } 
  }
}
//------------------------------------------------------------------------------
//
// Change claim eq
//
function tf_onchangeeq(cl,eqcl) {
  
  if(eqcl) {
    // check if eqcl is already point to someone else 
    if(GetClaimEq(eqcl)) {
      alert("Cannot set claim "+cl+" equal to "+eqcl+" because claim "+
	    eqcl+" is equal to claim "+GetClaimEq(eqcl));
      document.getElementById("EQ"+cl).value=GetClaimEq(cl);      
      return;
    }     
    // check if no one is pointing to me (cl)
    var eqiter= new Eq_claim_iterator(cl);
    if(!eqiter.end()) {
      alert("Cannot set claim "+cl+" equal to "+eqcl+" because claim "+
	    eqiter.getValue()+" is equal to claim "+cl);
      document.getElementById("EQ"+cl).value=GetClaimEq(cl);      
      return;
    }        
  }
  new_Taint(cl); 
  changeEq(cl,eqcl);

  // other errors ?
  if(GetClaimEq(cl) != eqcl) {
    document.getElementById("EQ"+cl).value=GetClaimEq(cl);      
    return;
  }


  var cl_iter= new claim_iterator(cl);
  while(!cl_iter.end()) {
    updatefromdocs(cl_iter.getValue());
    cl_iter.next();
  }   

  CheckClaimIntegrity(cl);

 // To be used when updating without reloading

  tf_updateclDESV(cl,MOD_CTF.seldoc);
  tf_updadetable(cl);
  html_setwhatis("whatclEQ"+cl,eqcl ? GetClaimDescription(eqcl) : "");
  html_setwarning("cleqwarn"+cl,GetClaimEqWarn(cl));
  html_setwarning("clgrpwarn"+cl,GetClaimGroupWarn(cl));
  html_setwarning("allwarn",(GetClaimsWarnings() >0 ) ? GetClaimsWarnings()+": warnings":"");
  tf_updatenotsearchedview();
}

//------------------------------------------------------------------------------

//
// Change TF description 
//

function tf_onchangefeature(cl,tf) {
  SetFeatureDesc(cl,tf,html_flexarea_selected().value);
  html_flexarea_selected().value=GetFeatureDesc(cl,tf);
}

//------------------------------------------------------------------------------

//
// Change TF EQ field 			 
//

function tf_onchangetfeq(cl,tf,val) {
  if(!featurechangeeq(cl,tf,val)) {
    document.getElementById("tfeq"+cl+"_"+tf).value=GetFeatureEq(cl,tf);
    return;
  }  
  if(GetFeatureWarn(cl,tf)) {
    tf_onresettfwarn(cl,tf);
  }
  
  tf_updatevalfromauto(cl,tf,MOD_CTF.seldoc);
  tf_updatetfTD11(cl,tf);  
  tf_updatetfTD21(cl,tf);  
  tf_updatetfTD22(cl,tf,MOD_CTF.seldoc);
}

//------------------------------------------------------------------------------

function tf_onchangeTD22(cl,tf) {
  var riter= new claim_features_riterator(cl,"",tf);
  do {
    tf_updatetfTD22(riter.getcl(),riter.gettf(),MOD_CTF.seldoc);
    var eq_iter=new EqTF_claim_iterator(riter.getcl(),riter.gettf());
    var cltf=riter.gettext();
    while(!eq_iter.end()) {
      var ccl=eq_iter.getValue();
      if( IsClaimInPage(ccl) && !GetClaimEq(ccl)) { 
	var tf_iter= new claim_features_iterator(ccl);
	// find tf(s) pointing to pcl.ptf
	while(!tf_iter.end()) { 
	  if(tf_iter.getEq()==cltf){
	    tf_updatetfTD22(tf_iter.getcl(),tf_iter.gettf(),MOD_CTF.seldoc);	  
	  }
	  tf_iter.next();
	}
      }  
      eq_iter.next();
    }
    riter.next();
  } while(!riter.end() && is_glue_hint(riter.getHint(MOD_CTF.seldoc)));
}

//------------------------------------------------------------------------------

//
// Change TF passage field 
//

function tf_onchangetfpassage(cl,tf,txt) {  
  // Update field 
  var hint=GetPassageHint(cl,tf,MOD_CTF.seldoc);
  if(is_param_hint(hint)){
    SetPassageHintParam(cl,tf,MOD_CTF.seldoc,hint,txt);
    tf_onchangeTD22(cl,tf);
  } else {
    featureupdatepassage(cl,tf,MOD_CTF.seldoc,txt);
    tf_onchangeTD22(cl,tf);
    tf_updatevalfromauto(cl,tf,MOD_CTF.seldoc);
  }
}


//------------------------------------------------------------------------------
//
// Changed TF hint
// 


function tf_onchangetfhintsel(cl,tf) {
  tf_onchangetfhint(cl,tf,html_selected("hint"+cl+"_"+tf,ALL_HINTS));
}
					 
function tf_onchangetfhint(cl,tf,newhintval) {
  featureupdatehints(cl,tf,MOD_CTF.seldoc,newhintval);
  tf_onchangeTD22(cl,tf);
  tf_updatevalfromauto(cl,tf,MOD_CTF.seldoc);
}

//------------------------------------------------------------------------------


//
// Change TF clarity
//

function tf_onchangetfclar(cl,tf) {  
  var newclarval=html_selected("clar"+cl+"_"+tf,CLAR_HINTS);    
  var cltf = cl+"."+tf;
  var ccl;

  featureupdateclarity(cl,tf,newclarval);
  tf_updatetfTD21(cl,tf);
  
  // find pointing claims and update them
  var eq_iter= new EqTF_claim_iterator(cl,tf);
  while(!eq_iter.end()) {
    ccl=eq_iter.getValue();
    var tf_iter= new claim_features_iterator(ccl);
    while(!tf_iter.end()) { 
      if(tf_iter.getEq() == cltf) {
 	featureupdateclarity(ccl,tf_iter.gettf(),newclarval);
        if(IsClaimInPage(ccl)) { // && !GetClaimEq(ccl)) {
	  tf_updatetfTD21(ccl,tf_iter.gettf());
        }   
      }
      tf_iter.next();
    }
    eq_iter.next();
  }
}
//------------------------------------------------------------------------------


//
// change TF import 
//

function tf_onchangetfimp(cl,tf,txt) {
  var imp = new claim_vtf(txt);    
  if(!imp.getver()) {
    imp.setver(html_selected_iter("tfimpver"));
  }
  featurechangeimp(cl,tf,imp.getValue());
  tf_updatetfTD11(cl,tf);
  tf_updatetfTD21(cl,tf);
  if(MOD_CTF.seldoc) {
    tf_updatetfTD22(cl,tf,MOD_CTF.seldoc);
    tf_updateclDESV(cl,MOD_CTF.seldoc);
  }
}

//------------------------------------------------------------------------------

function tf_onresettfwarn(cl,tf) {
  SetFeatureWarn(cl,tf,"");
  html_setwarning("tfwarn"+cl+"_"+tf,"");
  tf_updateglobalwarnings();
}

//------------------------------------------------------------------------------

function tf_onresetcleqwarn(cl) {
  alert("Change equivalence for claim "+cl);
}


function tf_onresetclgrpwarn(cl) {
  alert("Change equivalence or group for claim "+cl);
}

function tf_updateglobalwarnings(cl) {
  if(GetGroupsLength()>1) { 
    var clview_iter= new PageClaim_Iterator();
    while(!clview_iter.end()) {
      html_setwarning("clgrpwarn"+clview_iter.getValue(),GetClaimGroupWarn(clview_iter.getValue()));
      clview_iter.next();
    }
  }
  html_setwarning("allwarn",(GetClaimsWarnings() >0 ) ? GetClaimsWarnings()+": warnings":"");
}

function tf_onchangeclgroup(cl) {
  onchangegroup(cl);
  html_group_doselect("SG"+cl,GetClaimGroup(cl));
  tf_updateglobalwarnings();
  var clview_iter= new PageClaim_Iterator();
  while(!clview_iter.end()) {
    var cl=clview_iter.getValue();
    var clclass=ClaimTypeStyle(cl);
    document.getElementById("fdcltd"+cl).className=clclass;
    document.getElementById("fdbcltd"+cl).className=clclass;
    clview_iter.next();
  }      
}

// -----------------------------------------------------
// | claim | D E                               S X |    |
// -----------------------------------------------------
// | TD11  |    TD12                               |TD13|
// | TD21  |    TD22                               |    |
// |----------------------------------------------------



function tf_updateclDESV(cl,pn) {
  if(pn && IsClaimInPage(cl)) {
    var doc=Doc2DOCPNS(pn);    
    html_doselect("ssel"+cl+"_"+doc,CLSTRATS,GetClaimDocStrat(cl,pn));       
    html_doselect("vsel"+cl+"_"+doc,CLVALS,GetClaimDocVal(cl,pn)); 
    if(IsClaimDocValAuto(cl,pn)) {
      document.getElementById("vsel"+cl+"_"+doc).disabled=1;
    } else {
      document.getElementById("vsel"+cl+"_"+doc).disabled=0;
    }
  }
}


function tf_showtfTD11(cl,tf,tf_iter) {
  var eqclass="";
  var eqsize=6;

  var tfeq=tf_iter.getEq();

  if(tfeq) {   
    eqclass="eqtf";
    tfopts = " disabled";
  }     

  // make space for import tf 
  if(GetClaimSetVersion()>1) { 
    eqsize=1;
  }
  
  var html=new Array();
  var hi=0;
  //html.push("<fieldset><legend><b>TF "+cl+"."+tf+"</b></legend>");
  html[hi++]="<TABLE border=1 class='SMALLTAB "+eqclass+"' width=100% id='tabtf"+cl+"_"+tf+"'>";
  html[hi++]="<TR><TD align=center><b>TF "+tf_iter.getcl()+"."+tf_iter.getNum()+"</b></TD></TR><TR>";

  // TF EQ
  var eqtag="<b>E</b> ";
  var eqtxt="";
  
  if(tfeq) {
    var eqtf=new claim_tf(tfeq);
     eqtag+="<input type=text size="+eqsize+" value='"+tfeq+"' ";
     if(is_claim_tf(eqtf.getcl(),eqtf.gettf())) {
      eqtxt=GetFeatureDesc(eqtf.getcl(),eqtf.gettf());
     } else {
      eqtxt+="Unknown feature "+tfeq;
     }
  } else {
    eqtag+="<input type=text size="+eqsize+" value='' ";
  }
  eqtag  +="onChange='tf_onchangetfeq("+cl+","+tf+",this.value);' id='tfeq"+cl+"_"+tf+"'>";
  html[hi++]="<TD>"+html_whatis(eqtag,eqtxt,"whatEQ"+cl+"_"+tf);
  html[hi++]=html_warning("tfwarn"+cl+"_"+tf,GetFeatureWarn(cl,tf),"tf_onresettfwarn("+cl+","+tf+")");
  
  // TF Import 
  if(GetClaimSetVersion()>1) { 
    var imptf=GetFeatureImport(cl,tf);
    if(imptf) {
      var vtf=new claim_vtf(imptf);
      var whatag =" I <input type=text id='tfimp"+cl+"_"+tf+"' size="+(eqsize+3)+" ";
      whatag+="value='"+imptf+"' onChange='tf_onchangetfimp("+cl+","+tf+",this.value);'>";
      html[hi++]="<b>"+html_whatis(whatag,GlobalGetFeatureAttr(vtf.getver(),vtf.getcl(),vtf.gettf(),"desc"),
				   "whatIMP"+cl+"_"+tf)+"</b>";
    } else {
      var whatag =" I <input type=text id='tfimp"+cl+"_"+tf+"' size="+(eqsize+2)+" ";
      whatag+="value='' onChange='tf_onchangetfimp("+cl+","+tf+",this.value);'>";
      
      html[hi++]="<b>"+html_whatis(whatag,"","whatIMP"+cl+"_"+tf)+"</b>";
    }
    //html[hi++]=" I <input type=text id='tfimp"+cl+"_"+tf+"' size="+(eqsize+2)+" ";
    //html[hi++]="value='"+imptf+"' onChange='tf_onchangetfimp("+cl+","+tf+",this.value);'>";
  }	
  html[hi]="</TD></TR></TABLE>";
  return html.join('');
}

function tf_updatetfTD11(cl,tf) {
  var tfeq=GetFeatureEq(cl,tf);
  if(tfeq) {
    var eqtf=new claim_tf(tfeq);
    document.getElementById("tfeq"+cl+"_"+tf).value=tfeq;
    document.getElementById("tabtf"+cl+"_"+tf).className="eqtf";
    html_setwhatis("whatEQ"+cl+"_"+tf,GetFeatureDesc(eqtf.getcl(),eqtf.gettf()));
  } else {
    document.getElementById("tfeq"+cl+"_"+tf).value="";;
    document.getElementById("tabtf"+cl+"_"+tf).className="";
    html_setwhatis("whatEQ"+cl+"_"+tf,"");
  }
  if(GetClaimSetVersion()>1) { 
    var imptf=GetFeatureImport(cl,tf);
    if(imptf) {
      var vtf=new claim_vtf(imptf);      
      html_setwhatis("whatIMP"+cl+"_"+tf,GlobalGetFeatureAttr(vtf.getver(),vtf.getcl(),vtf.gettf(),"desc"));    
    } else {
      html_setwhatis("whatIMP"+cl+"_"+tf,"");    
    }
    document.getElementById("tfimp"+cl+"_"+tf).value=imptf;
  }
}


function getFeatureClass(cl,tf) {
  if(GetFeatureSkip(cl,tf)) {
    return "featSkip";
  }
  if(GetFeatureEq(cl,tf)) {
    return "featEq";
  }
  return "featNorm";
}

function tf_showtfTD12(cl,tf,tf_iter,eq) {
  return html_splitflexarea(tf_iter.getDesc(),
			    "tf_onchangefeature("+cl+","+tf+");",
			    "class='"+getFeatureClass(cl,tf)+"' id='tftxtarea"+cl+"_"+tf+"'",
			    64,2);  
}

function tf_updatetfTD12(cl,tf) {
  document.getElementById("tftxtarea"+cl+"_"+tf).className=getFeatureClass(cl,tf);
}

function tf_showtfTD13(cl,tf,clfull) {  
  var html="<TABLE height=100% class=SMALLTAB><TR><TD valign=top>";
  if(tf==1) {
    if(claim_isdependent(cl)) { // use pure dependency
      if(!GetClaimHeader(cl)) {
	html+="<button onClick='tf_onstripheader("+cl+");'>"+
	  html_img(striphead_img,""," ALT='Strip header at cursor'")+"</button>";
      } else {
	html+="<button onClick='tf_onjoinheader("+cl+")'>"+
	  html_img(jointf_img,"","ALT='Undo strip header'")+"</button>";	
      }
    }
  } else {
    html+="<button onClick='tf_onjointf("+cl+","+tf+(clfull ? (","+clfull): "")+");'>"+html_img(jointf_img)+"</button>";
  };
  html+="</TD><TR><TD valign=bottom>";
  html+="<button onClick='tf_onsplittf("+cl+","+tf+(clfull ? (","+clfull): "")+");'>"+html_img(splittf_img)+"</button>";
  html+="</TD></TR></TABLE>";
  return html;
}


function tf_showtfTD21(cl,tf,tf_iter,eq) {
  var html="";
  // TF Clarity   
  var unclar=tf_iter.getUnclarityEq();//GetFeatureUnclarityEq(cl,tf);
  if(unclar) {
    // eval("clar_epc_"+unclar+"("+cl+")")
    var preview=stdcls_preview("clarity",unclar,cl,tf_iter.getDesc(),GetDossierLang(),GetClaimSetLaw());
    //alert("clarity "+unclar+" "+cl+" "+tf_iter.getDesc()+" =>"+preview);
    html=html_whatis("<b> C </b> ",preview,"whatCLAR"+cl+"_"+tf);
  } else {
    html=html_whatis("<b> C </b> ","","whatCLAR"+cl+"_"+tf);
  }
  html+=html_selection("clar"+cl+"_"+tf,CLAR_HINTS,
		       unclar,
		       "tf_onchangetfclar("+cl+","+tf+");",
		       tf_iter.getEq() ? " disabled " : "");
  
  return html;
}

function tf_updatetfTD21(cl,tf) {
  var eqtf=GetFeatureEq(cl,tf);
  var eqdesc="";
  var unclar;
  if(eqtf) {
    var tfeq=new claim_tf(eqtf);
    unclar=GetFeatureUnclarity(tfeq.getcl(),tfeq.gettf());
    eqdesc=GetFeatureDesc(tfeq.getcl(),tfeq.gettf());
    document.getElementById("clar"+cl+"_"+tf).disabled=1;
  } else {
    unclar=GetFeatureUnclarity(cl,tf);
    document.getElementById("clar"+cl+"_"+tf).disabled=0;
  }
  if(unclar) {
    // eval("clar_epc_"+unclar+"("+cl+")")
    var preview=stdcls_preview("clarity",unclar,cl,GetFeatureDesc(cl,tf),GetDossierLang(),GetClaimSetLaw());
    html=html_setwhatis("whatCLAR"+cl+"_"+tf,preview);
  } else {
    html=html_setwhatis("whatCLAR"+cl+"_"+tf,"");
  }
  html_doselect("clar"+cl+"_"+tf,CLAR_HINTS,unclar || ""); 
  html_setwhatis("whatEQ"+cl+"_"+tf,eqdesc);  
}
  

function getPassClass(cl,tf,pn) {
  if(pn) {
    var hint;
    if(GetFeatureEq(cl,tf)) {
      return "passEq";
    } else if (hint=GetPassageHintIgn(cl,tf,pn)) {
      if(is_skip_hint(hint)) {
	return "passSkip";
      } else if(is_notpresent_hint(hint)){	
	return "passHint";
      }
    }
    if(GetPassageReferenceEqIgn(cl,tf,pn) /*GetPassageReference(cl,tf,doc)*/ || is_present_hint(hint)){
      return "passPresent";
    }
  }
  return "passEmtpy";
}


function tf_showtfTD22(cl,tf,tf_iter,eq) {
  var html=new Array();  
  var hi=0;
  var hint="";
  var pass="",label="Hint Args",readonly="",italic="style='font-style:italic'",center="";
  // TF Passages for seldoc document 
 
  if(MOD_CTF.seldoc !="" && !eq) {
    if(tf_iter.getEq())  {
      var eqtf=new claim_tf(tf_iter.getEq());
      if(is_claim_tf(eqtf.getcl(),eqtf.gettf())) {
	hint=GetPassageHintIgn(eqtf.getcl(),eqtf.gettf(),MOD_CTF.seldoc);
	if(hint) {
	  if(is_param_hint(hint)) {
	    label="Args";
	    pass=GetPassageHintParam(eqtf.getcl(),eqtf.gettf(),MOD_CTF.seldoc,hint);
	  }  else if(is_glue_hint(hint)) {
	    label=html_img(img_chain);
	    center="align='center'";
	    pass=GetPassageReferenceIgn(eqtf.getcl(),eqtf.gettf(),MOD_CTF.seldoc);
	  } else {
	    label="Empty";
	    pass="";
	  }
	} else {
	  label="Passage";
	  pass=GetPassageReference(eqtf.getcl(),eqtf.gettf(),MOD_CTF.seldoc);
	}
	if(is_glue_hint(hint)){ // do not delete !
	  hint="";
	}
      } else {
	readonly="disabled";
      }
    } else {
      hint=GetPassageHint(cl,tf,MOD_CTF.seldoc);
      if(hint) {
	label="Args";
	if(is_param_hint(hint)) {	
	  pass=GetPassageHintParam(cl,tf,MOD_CTF.seldoc,hint);
	  italic="";
	} else if(is_glue_hint(hint)) {
	  center="align='center'";
	  label=html_img(img_chain);
	  pass="";
	  readonly="disabled";
	  italic="";
	} else {
	  pass="";
	  readonly="disabled";
	}
      } else {
	label="Passage";
	pass=tf_iter.getPassage(MOD_CTF.seldoc);
	italic="";
      }    
 
    }
    html[hi++]="<TABLE width=100% class=SMALLTAB><TR>";
    html[hi++]="<TD width=55 "+center+"><span id='passit"+cl+"_"+tf+"' "+italic+">"+label+"</span></TD>";
    html[hi++]="<TD align=right><input type=text size=79 value='"+pass+"' "+readonly;
    html[hi++]=" class='"+getPassClass(cl,tf,MOD_CTF.seldoc)+"' ";
    html[hi++]=" id='passref"+cl+"_"+tf+"' ";
    html[hi++]=" onChange='tf_onchangetfpassage("+cl+","+tf+",this.value)' tabindex="+cl+"></TD>";
    html[hi++]="<TD width=110><b> H </b>"+html_selection("hint"+cl+"_"+tf,ALL_HINTS, hint,
						  "tf_onchangetfhintsel("+cl+","+tf+")",
						  tf_iter.getEq() ? " disabled" : "");
    html[hi++]="</TD></TR></TABLE>";
  }
  
  return html.join('');
}



function tf_updatetfTD22(cl,tf,pn) {
  var teq=GetFeatureEq(cl,tf);
  if(!GetClaimEq(cl)) { // ignore updates 
    if(teq) { // eq feature
      var cltf= new claim_tf(teq);
      document.getElementById("passref"+cl+"_"+tf).disabled=1;
      document.getElementById("passit"+cl+"_"+tf).style.fontStyle="italic";
      if(pn) {	
	document.getElementById("passref"+cl+"_"+tf).value=GetPassageReferenceIgn(cltf.getcl(),cltf.gettf(),pn);
	document.getElementById("hint"+cl+"_"+tf).disabled=1;
	document.getElementById("passref"+cl+"_"+tf).className=getPassClass(cl,tf,pn);
	html_doselect("hint"+cl+"_"+tf,ALL_HINTS,GetPassageHintIgn(cltf.getcl(),cltf.gettf(),pn));	
      }    
    } else { // no eq feature      
      if(pn) {
	var hintval=GetPassageHint(cl,tf,pn);
	document.getElementById("passref"+cl+"_"+tf).disabled=0;
	if(hintval) {
	  document.getElementById("passref"+cl+"_"+tf).value="";
	  if(is_skip_hint(hintval)) {
	    document.getElementById("passref"+cl+"_"+tf).disabled=1;
	    document.getElementById("passit"+cl+"_"+tf).style.fontStyle="italic";	
	  } else if(is_glue_hint(hintval)) {
	    document.getElementById("passref"+cl+"_"+tf).disabled=1;
	    document.getElementById("passit"+cl+"_"+tf).style.fontStyle="italic";
	  } else if(is_param_hint(hintval)){
	    document.getElementById("passit"+cl+"_"+tf).style.fontStyle="normal";
	    document.getElementById("passref"+cl+"_"+tf).value=GetPassageHintParam(cl,tf,pn,hintval);
	    document.getElementById("passit"+cl+"_"+tf).innerText="Hint Args";
	  } else {
	    document.getElementById("passit"+cl+"_"+tf).innerText="Hint Args";
	    document.getElementById("passref"+cl+"_"+tf).disabled=1;
	    document.getElementById("passit"+cl+"_"+tf).style.fontStyle="italic";	
	  }
	} else  { // no hint, just passage
	  document.getElementById("passit"+cl+"_"+tf).style.fontStyle="normal";	
	  document.getElementById("passref"+cl+"_"+tf).value=GetPassageReference(cl,tf,pn);
	  document.getElementById("passit"+cl+"_"+tf).innerText="Passage";
	}
	document.getElementById("hint"+cl+"_"+tf).disabled=0;
	html_doselect("hint"+cl+"_"+tf,ALL_HINTS,hintval); 	
      }
      document.getElementById("passref"+cl+"_"+tf).className=getPassClass(cl,tf,pn);
    }
    document.getElementById("tftxtarea"+cl+"_"+tf).className=getFeatureClass(cl,tf);   
  }
}


//------------------------------------------------------------------------------
//
// render info for one claim , for one doc 
//
function tf_showalltf(cl,pn,clfull) {
  var eq=GetClaimEq(cl);
  var html=new Array();
  var hi=0;
  var tf_iter= new claim_features_iterator(cl);
  
  if(GetClaimHeader(cl)) {
    html[hi++]="<TR><TD></TD><TD>"+ html_flexarea(GetClaimHeader(cl),"tf_onchangeheader("+cl+");",
						  "class='ROTXT' id='tftxtarea"+cl+"_0'",
						 64)+"</TD></TR>";
    //html.push("<TD><TABLE height=100%><TR><TD valign=top></TD></TR></TABLE></TD></TR>");
    
  }
  while(!tf_iter.end()) { 
    var tfeq=tf_iter.getEq();
    var tf=tf_iter.getValue();
    html[hi++]="<TR id='clrow"+cl+"_"+tf+"'>";
    html[hi++]="<TD style='border-bottom-width:0;'>"+tf_showtfTD11(cl,tf,tf_iter)+"</TD>";  
    html[hi++]="<TD valign=bottom style='border-bottom-width:0;'>"+tf_showtfTD12(cl,tf,tf_iter,eq)+"</TD>";
    html[hi++]="<TD valign=top rowspan=2>"+tf_showtfTD13(cl,tf,clfull)+"</TD>";  
    
    html[hi++]="</TR><TR style='border-top-width:0;'>"; 
    html[hi++]="<TD style='border-top-width:0;'>"+tf_showtfTD21(cl,tf,tf_iter,eq)+"</TD>"; 
    html[hi++]="<TD align=right  valign=bottom style='border-top-width:0;' id='tdtfeq"+cl+"_"+tf+"'>"+tf_showtfTD22(cl,tf,tf_iter,eq)+"</TD>";
    html[hi++]="<TD align=left valign=bottom ></TD></TR>";      
    tf_iter.next();
  }
  
  return html.join('');
}

MOD_CTF.FULLVIEW=new Array();
MOD_CTF.tf_swfullview=function(cl,v) {
  MOD_CTF.FULLVIEW[cl]=v;
  edit_features();
}
   
MOD_CTF.EQFOCUS=0;

function tf_showclaimfeaturesfordoc(cl,pn,tabidxdep,tabidxeq) {
  var warnclass="HIDEME";
  var clclass=ClaimTypeStyle(cl);
  var html=new Array();

  var eq=GetClaimEq(cl);
  html.push("<TR><TD id='fdcltd"+cl+"' class='"+clclass+"' style='border-top-width:2;' width=115>");
  html.push("<button style='width:100%;margin:0 0 0 0;' id='fdbcltd"+cl+"'");
  html.push(" class='"+clclass+"' onClick='tf_onclickonclaim("+cl+");'>");
  html.push("Claim "+cl+" <sup>"+GetClaimDep(cl)+"</sup></button>");
	    
  //html.push("<input type=button id='fdbcltd"+cl+"'  class='"+clclass+"' ");
  //html.push("value='Claim "+cl+"' onClick='tf_onclickonclaim("+cl+");'>");

  html.push("</TD><TD style='border-top-width:2;'><TABLE border=0 width=100%><TR>");
  html.push("<TD align=left >"); //width=32%
  // Claim DEP
  //html.push("<b>D</b> <input type=text TABINDEX="+tabidxdep);
  //html.push(" class=DEPEQ align=center disabled value='"+GetClaimDep(cl)+"' id='DEP"+cl+"'> ");
  // Claim EQ
  if(eq) {
    html.push(html_whatis("<b>E</b>",GetClaimDescription(eq),"whatclEQ"+cl));
  } else {
    html.push(html_whatis("<b>E</b>","","whatclEQ"+cl));
  }

  html.push(" <input type=text TABINDEX="+tabidxeq+" class=DEPEQ value='"+eq+"' ");
  html.push(" id=EQ"+cl+" onFocus='MOD_CTF.EQFOCUS="+cl+";' onChange='tf_onchangeeq("+cl+",this.value);'>");	
  
  html.push(" "+html_warning("cleqwarn"+cl,GetClaimEqWarn(cl),"tf_onresetcleqwarn("+cl+")"));
  
  // Claim Group
  if(GetGroupsLength()>1) {
    html.push(" <b>G</b>"+group_select(cl,"tf_onchangeclgroup"));
    // Warn Info
    html.push(" "+html_warning("clgrpwarn"+cl,GetClaimGroupWarn(cl),"tf_onresetclgrpwarn("+cl+")"));
  }

  html.push("</TD>");
  html.push("<TD align=center class='CLHEADER' style='border-top-width:2;'>Feature Description </TD>");//width=45%

  // Strategy and Value for current document
  if(pn) {      
    var doc=Doc2DOCPNS(pn);
    var opts= eq ? " disabled ":"";
    html.push("<TD align=right >"); //width=25%
    html.push("<b>S </b>"+html_selection_ns("ssel"+cl+"_"+doc,    
					 CLSTRATS,
					 GetClaimDocStrat(cl,pn,eq),
					 "tf_onchangestrat("+cl+","+doc+")",opts));
 
    if(IsClaimDocValAuto(cl,pn)) {
      opts=" disabled ";
    } 
    html.push("<b> V </b>"+html_selection_ns("vsel"+cl+"_"+doc,
					  CLVALS,
					  GetClaimDocVal(cl,pn,eq),
					  "tf_onchangeval("+cl+","+doc+")",opts)+"</TD>");
  }

  html.push("</TR></TABLE></TD>");

  // Show/ Hide full claim features (including feature from parent claims)
  if(claim_isdependent(cl)) { // do not use group independency
    html.push("<TD align=center style='border-top-width:2;'>");        
    if(MOD_CTF.FULLVIEW[cl]) {           
      html.push("<button onclick='MOD_CTF.tf_swfullview("+cl+",0);'>"+html_img(fullview_img)+"</button></TD>");
    } else {
      html.push("<button onclick='MOD_CTF.tf_swfullview("+cl+",1);'>"+html_img(compactview_img)+"</button></TD>");
    }
  }
  html.push("</TR>");

  if(MOD_CTF.FULLVIEW[cl]) {
    var uhtml="";
    var clup=GetClaimDep(cl);
    while(dep_isdependent(clup)) {
      uhtml=tf_showalltf(clup,pn,cl)+uhtml;
      clup=GetClaimDep(clup);
    }
    html.push(uhtml);
  } 
  html.push(tf_showalltf(cl,pn));  
  
  return html;
}

//
// render for all claims for one doc 
// 


function tf_showfeaturesfordoc(pn){
  CURRENTVIEW="tfview";
  var html=new Array();
  html.push("<TABLE border=2 CELLSPACING=0 id=bigcltable>");
  //html+=""hidevars(0);
  var pcl_iter=new PageClaim_Iterator();
  var tabidx= new tab_iterator();

  while(!pcl_iter.end()) {
    html.push("<div id=cldiv"+pcl_iter.getValue()+">");
    html=html.concat(tf_showclaimfeaturesfordoc(pcl_iter.getValue(),pn,tabidx.getDep(),tabidx.getEq()));
    html.push("</div>"); 
    pcl_iter.next();
    tabidx.next();
  }

  
  html.push("</TABLE>");
  return html; 
}

function tf_updatenotsearchedview() {
  ClaimToolNoOp();
}

MOD_CTF.tf_onchangetfimpver=function() {
  MOD_CTF.tfimpver   =html_selected_iter("tfimpver");
}

MOD_CTF.info=function() {
  var html="";
  if(MOD_CTF.seldoc!="Add") {
    html= html_warning("allwarn",(GetClaimsWarnings() >0 ) ? GetClaimsWarnings()+": warnings":"");
    html+=ClaimToolNoOp("html");
  }  
  return html;
}

MOD_CTF.extra=function() {
  var html="";
  if(GetClaimSetVersion()>1 && MOD_CTF.seldoc!="All" && MOD_CTF.seldoc!="Add") {
    html+="<fieldset><legend>Import</legend>";
    html+="TF from V"+html_selection_iter("tfimpver",
					  new range_iterator(1,GetClaimSetVersion()-1),
					  MOD_CTF.tfimpver,"MOD_CTF.tf_onchangetfimpver()");
    html+="</fieldset>";
  }
  return html;
}

MOD_CTF.showalldocs=function() {
  MOD_CTF.seldoc=html_tabs_obj_selected("editft");
  SetClaimToolEditSectionExtra(MOD_CTF.extra());
  SetClaimToolEditSectionInfo(MOD_CTF.info()); 
  return tfall_showfeaturesforclaims().join('');
}

MOD_CTF.showdoc=function(){
  var prevdoc=MOD_CTF.seldoc;
  MOD_CTF.seldoc=html_tabs_obj_selected("editft");
  if((prevdoc=="All" || prevdoc=="Add")) {
    SetClaimToolEditSectionExtra(MOD_CTF.extra("showdoc"));
    SetClaimToolEditSectionInfo(MOD_CTF.info());
  }
  return tf_showfeaturesfordoc(MOD_CTF.seldoc).join('');
}

MOD_CTF.shownodocs=function(){
  var prevdoc=MOD_CTF.seldoc;
  MOD_CTF.seldoc="";
  if((prevdoc=="All" || prevdoc=="Add")) {
    SetClaimToolEditSectionExtra(MOD_CTF.extra("showdoc"));
    SetClaimToolEditSectionInfo(MOD_CTF.info());
  }
  return tf_showfeaturesfordoc(MOD_CTF.seldoc).join('');
}

MOD_CTF.adddoc=function(){
  MOD_CTF.seldoc=html_tabs_obj_selected("editft");
  SetClaimToolEditSectionExtra("");
  SetClaimToolEditSectionInfo("");
  return edit_docs(edit_features); 
}

function edit_features(pn) {  
  if(CORRUPTEDDOS) {
    CheckClaimSetIntegrity();
    CORRUPTEDDOS=0;
  }
  InitDocPNS();
  InitDocPNAll();

  ACT_MOD= MOD_CTF;

  if(!CLAIMSET) {
    alert("Create or Select a claim set first !");
    return;
  }
  if(pn) {
    MOD_CTF.seldoc=pn;
  }

  // Perf mesure 1/2  
  //var start = new Date().getTime();

  MOD_CTF.tab=[];
  var viewdocs=0;
  var doc_iter=new doc_iterator();
  while(!doc_iter.end()) {
    if(!doc_iter.isNotCited()) {
      viewdocs++;
      MOD_CTF.tab[doc_iter.getPN()]={
	yeslabel:html_whatis(doc_iter.getPN(),doc_iter.getTitle()),
	nolabel:html_whatis(doc_iter.getPN(),doc_iter.getTitle(),"","popupbg"),
	callback:MOD_CTF.showdoc
      }
    }
    doc_iter.next();    
  }
  if(viewdocs) {
    MOD_CTF.tab["All"]={
      yeslabel:html_whatis("All","All documents at once"),
      nolabel:html_whatis("All","All documents at once","","popupbg"),
      callback:MOD_CTF.showalldocs
    }  
  } else {
    MOD_CTF.tab["Features"]={
      callback:MOD_CTF.shownodocs
    }
  }
  MOD_CTF.tab["Add"]={
    label:"<TABLE width=100%><TR><TD align=center>"+html_img(add_img)+"<TD></TR></TABLE>",
    callback:MOD_CTF.adddoc
  }

  if(GetClaimSetVersion()>1) {
    MOD_CTF.tfimpver   =html_selected_iter("tfimpver",MOD_CTF.tfimpver);
  } 
  /* 
  var html="<TABLE><TR valign=middle><TH align=left>"+filter_selection("edit_features()")+"</TH>"; 
  html+="<TH align=right id=cltfbar>"+MOD_CTF.bar("main")+"</TH></TR><TR><TD colspan=2>";
  html+=html_tabs_obj("editft",MOD_CTF.tab,MOD_CTF.seldoc)+"</TD></TR></TABLE>"; 
  */
  //alert(new Date().getTime() - start);  
  ClaimToolEditFilterSection("Edit Tecnical Features",
		       html_tabs_obj("editft",MOD_CTF.tab,MOD_CTF.seldoc),
		       "edit_features()","",MOD_CTF.seldoc,"",MOD_CTF.info(),MOD_CTF.extra("main"));
}

function printtfview() {
  var html="<TABLE class='LISTTXTCL' style='border-spacing:5px 40px;'>";
  var cl_iter =  new filteredclaims_iterator();
  while(!cl_iter.end()) {
   var tf_iter= new claim_features_iterator(cl_iter.getValue());
   html+="<TR><TD VALIGN=top class='LISTTXTCL'>"+cl_iter.getValue();
   html+=". </TD>";
   while(!tf_iter.end()) {
     html+="<TD style='border-right:1px solid black;spacing:1px 1px 10px 20px;'><small>"+tf_iter.gettext()+"</small></TD>";
     html+="<TD VALIGN=top class='LISTTXTCL' style='padding-left:10px;'>"; 
     switch(tf_iter.getUnclarity()) {
     case "added":
       html+="<u>"+tf_iter.getDesc()+"</u>";
       break;
     case "broad":
     case "vague":
       html+="<i>"+tf_iter.getDesc()+"</i>";
       break;
     default:
       html+=tf_iter.getDesc();
     }
     html+="</TD></TR><TR><TD></TD>";
     tf_iter.next();
   }   
   html+="<TD>&nbsp<BR>&nbsp</TD></TR>";
   cl_iter.next();
  }
  html+="</TABLE>";
  return html;
}
